'use strict';

angular.module('afasApp')
  .controller('CountriesCtrl', ['$scope', 'Services', '$state', function ($scope, Services, $state) {

    $scope.countries = [];
    $scope.countryNew = {};
    $scope.params = {};
    $scope.errors = {};

    // PAGINATION
    // $scope.pagesize = 10;

    // $scope.pagination = {
    //   current: 1
    // };

    // $scope.pageChanged = function(newPage) {
    //   getResultsPage(newPage);
    // };

    // function getResultsPage(pageNumber) {
    //   var data = $scope.params;
    //   data.pagesize = $scope.pagesize;
    //   data.page = (pageNumber - 1);
    //   $scope.pagination.current = pageNumber;
    //   Services.getItems('countries', data)
    //   .then(function( results ) {
    //     console.log(results.headers);
    //     var pagingData = angular.fromJson(results.headers['x-pagination']);
    //     $scope.totalItems = pagingData.TotalCount;
    //     $scope.countries = results.data;
    //   });
    // }
    // getResultsPage(1);


    function applyRemoteData( newData ) {
      $scope.countries = newData;
    }

    function loadRemoteData() {
      Services.getItems('countries')
      .then(function( results ) {
        applyRemoteData( results.data );
      });
    }

    loadRemoteData();

    $scope.addCountry = function () {
      $scope.errors = {};
      Services.add('countries', $scope.countryNew)
      .then(function(){
        $scope.countryNew = {};
        $state.go( '^.list' );
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };

    $scope.deleteCountry = function (country) {
      Services.delete('countries', country)
      .then(function(){
        loadRemoteData();
      });
    };
  }]).controller('CountryCtrl', ['$scope', 'Services', '$state', '$stateParams', function ($scope, Services, $state, $stateParams) {

    $scope.country = {};
    $scope.currentID = $stateParams.id;

    Services.getItem('countries', $stateParams.id)
    .then(function(results){
      $scope.country = results.data;
    });

    $scope.updateCountry = function () {
      Services.update('countries', $scope.country, $scope.currentID)
      .then(function(){
        $state.go( '^' );
      });
    };
  }]);